package tothreedesignmodel.singleton;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 枚举可防止反射破坏
 *
 * @Author lzhphantom
 * @Description
 * @Date 创建于 14:21 2020/7/17
 * @Modified
 */
public class EnumSingletonTest {

    /**
     * 反射进行破坏枚举，失败
     *
     * @param
     * @return void
     * @description
     * @method reflectTest
     * @author lzhphantom
     * @date 15:00 2020/7/17
     */
    public static void reflectTest() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
        EnumSingleton s1 = EnumSingleton.INSTANCE;
        EnumSingleton s2 = EnumSingleton.INSTANCE;
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        Constructor<EnumSingleton> declaredConstructor = EnumSingleton.class.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);
        // IllegalArgumentException --阻止反射破坏
        EnumSingleton s3 = declaredConstructor.newInstance("123", 66);
        System.out.println(s3.hashCode());
    }

    /**
     * 序列化进行破坏--失败
     *
     * @param
     * @return void
     * @description
     * @method serializable
     * @author lzhphantom
     * @date 15:00 2020/7/17
     */
    public static void serializable() throws IOException, ClassNotFoundException {
        EnumSingleton instance = EnumSingleton.INSTANCE;
        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("enumTest.obj"));
        outputStream.writeObject(instance);
        outputStream.flush();
        outputStream.close();

        FileInputStream inputStream = new FileInputStream("enumTest.obj");
        ObjectInputStream stream = new ObjectInputStream(inputStream);
        EnumSingleton o = (EnumSingleton) stream.readObject();
        stream.close();
        // 2133927002
        System.out.println(instance.hashCode());
        // 2133927002
        System.out.println(o.hashCode());

    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException, ClassNotFoundException {
        // reflectTest();
        serializable();
    }
}
